package jmind.core.manager;

import jmind.core.jdbc.DataSourceFactory;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.concurrent.FutureTask;

public class JdbcManager extends AbstractManager<JdbcTemplate> {
    // volatile 解决 双重检测锁DCL(Double Check Lock) 问题
    private static volatile JdbcManager manager;

    public static JdbcManager getInstance() {
        if (manager == null) {
            synchronized (JdbcManager.class) {
                if (manager == null) {
                    manager = new JdbcManager();
                }
            }
        }
        return manager;
    }

    @Override
    public JdbcTemplate create(final String name) {
        final DataSource ds = DataSourceFactory.createFactory(getProperties().getProperty("jdbc." + name + ".datasource")).getSource(name,getProperties());
        return new JdbcTemplate(ds);
    }

    @Override
    public void releaseResource() {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                for (FutureTask<JdbcTemplate> source : RESOURCES.values()) {
                    try {
                        BasicDataSource ds = (BasicDataSource) source.get().getDataSource();
                        ds.close();
                    } catch (Exception e) {
                        logger.error("", e);
                    }

                }
                logger.debug("releaseResource {}", getClass().getName());
            }
        });

    }
}
